from ronglian_sms_sdk import SmsSDK
from flask import current_app
import json, redis


class SmsTool():
    """
    发送短信类
    """

    def __init__(self):
        accId = current_app.config.get('RL_ACC_ID')  # 主账户ID
        accToken = current_app.config.get('RL_ACC_TOKEN')  # 账户授权令牌
        appId = current_app.config.get('RL_APP_ID')  # 默认
        # 实例化SmsSDK
        self.sdk = SmsSDK(accId, accToken, appId)

        host = current_app.config.get('REDIS_HOST')
        port = current_app.config.get('REDIS_PORT')
        self.red = redis.Redis(host=host, port=port)

    def send(self, phone, code):
        """

        :param phone:
        :param code:
        :return:
        """

        tid = current_app.config.get('RL_TID')
        # 有效期
        t = current_app.config.get('SMS_TIME')
        datas = (code, t)

        # 存储redis
        self.red.set(phone, code, ex=t * 60)

        # 发送短信验证码
        rs = self.sdk.sendMessage(tid, phone, datas)  # 返回的是JSON字符串
        rs_data = json.loads(rs)
        if rs_data['statusCode'] == '000000':
            return True
        return False


# if __name__ == '__main__':
#     # 开启上下文换进
#     from app import app
#
#     with app.app_context():
#         s = SmsTool()
#         rs = s.send('17559511990', '6666')
#         print(rs)
